package com.nageoffer.shortlink.admin.toolkit;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 打印excel
 */
public class EasyExcelWebUtil {

    /**
     * 向浏览器写入excel数据
     * @param response 响应
     * @param fileName 文件名
     * @param  clazz 写入的类
     * @param data 写入的数据
     */
    @SneakyThrows
    public static void write(HttpServletResponse response, String fileName, Class<?> clazz, List<?> data) {
        response.setContentType("application/vad.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+","20%");
        response.setHeader("Content-Disposition","attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(),clazz).sheet("Sheet").doWrite(data);
    }
}
